<!--  -->
<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
    <el-breadcrumb-item>权限管理</el-breadcrumb-item>
    <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图 -->
    <el-card>
        <el-row>
            <el-button type="primary" @click="showRoleDialog">添加角色</el-button>
        </el-row>
        <!-- 角色列表区域 -->
        <el-table :data="rolelist" :border="true" :stripe="true">
            <!-- 展开列 -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row :class="['bdbottom',i1 === 0 ? 'bdtop': '', 'vertical-center' ]" v-for="(item1,i1) in scope.row.children" :key="item1.id" type="flex" align='top'>
                        <!-- 渲染一级权限 -->
                        <el-col :span="5" >
                            <el-tag closable @close="removeRightById(scope.row, item1.id)">{{ item1.authName }}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级和三级权限 -->
                        <el-col :span="19">
                            <!-- 通过for 嵌套渲染二级权限 -->
                            <el-row :class="['bdbottom', i2 === 0 ? 'bdtop':'','vertical-center']" v-for="(item2, i2) in item1.children" :key="item2.id">
                                <el-col :span="6">
                                    <el-tag closable @close="removeRightById(scope.row, item2.id)" type="success">{{ item2.authName }}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <!-- 三级标签 -->
                                <el-col :span="18">
                                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id"
                                    closable @close="removeRightById(scope.row, item3.id)">{{ item3.authName }}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <el-table-column type="index"></el-table-column>
            <el-table-column label="角色名词" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作" width="300px">
                <!-- 编辑、删除、分配权限功能操作 -->
                <template slot-scope="scope">
                    <el-button size='mini' type="primary" icon="el-icon-edit" @click="editRoleById(scope.row.id)">编辑</el-button>
                    <el-button size='mini' type="danger" icon="el-icon-delete" @click="deleteRoleById(scope.row.id)">删除</el-button>
                    <el-button size='mini' type="warning" icon="el-icon-setting" @click="showRightDailog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>
    </el-card>

    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addDialogFormVisible" @close="addDialogClosed" width="50%">
    <el-form :model="addForm" :rules="editFormRules" ref="addFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
    </el-form>
        <div slot="footer" class="dialog-footer">
        <el-button @click="addDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRoleInfo">确 定</el-button>
        </div>
    </el-dialog>

    <!-- 编辑角色对话框 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogFormVisible" width="50%">
    <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
        <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRoleInfo">确 定</el-button>
    </div>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
    title="分配权限"
    :visible.sync="rightDialogVisible"
    width="50%"
    @close="rightDialogClosed">
    <el-tree :data="rightslist" :props="defaultProps"
    @node-click="handleNodeClick"
    :show-checkbox="true"
    node-key="id"
    :default-expand-all="true"
    :default-checked-keys="defaultkeys"
    ref="treeRef"></el-tree>
    <span slot="footer" class="dialog-footer">
        <el-button @click="rightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="rightInfo">确 定</el-button>
    </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
    //   角色列表
      rolelist: [],
      //   添加角色对话框显示、隐藏
      addDialogFormVisible: false,
      //   添加角色规则 和 编辑一样
      addForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑对话框显示 隐藏
      editDialogFormVisible: false,
      //   编辑表单
      editForm: {
        roleName: '',
        roleDesc: ''
      },
      //   编辑表单规则
      editFormRules: {
        roleName: [{ required: true, message: '角色名称不能为空', trigger: ['blur', 'change'] }],
        roleDesc: [{ max: 50, message: '最大长度50', trigger: 'blur' }]
      },
      // 编辑角色id
      roleId: '',
      // 分配权限对话框显示、隐藏
      rightDialogVisible: false,
      // 权限列表
      rightslist: [],
      // 树形结构配置
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 树型节点默认展开的数组
      defaultkeys: []
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    async getRoleList () {
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取角色列表失败')
      //   this.$message.success('获取角色列表成功')
      this.rolelist = res.data
      console.log(this.rolelist)
    },
    // 删除角色的权限
    async removeRightById (role, rightId) {
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult !== 'confirm') return this.$message.info('取消删除')
      const { data: delres } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (delres.meta.status !== 200) return this.$message.err('删除失败')
      this.$message.success('删除成功')
      //   this.getRoleList()
      role.children = delres.data
    },
    // 删除角色
    async deleteRoleById (roleId) {
      const confirmRes = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRes !== 'confirm') return this.$message.info('取消删除')
      const { data: delRes } = await this.$http.delete('roles/' + roleId)
      if (delRes.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 编辑角色对话框弹出
    async editRoleById (roleId) {
    //   console.log(role)
      const { data: getRes } = await this.$http.get('roles/' + roleId)
      if (getRes.meta.status !== 200) {
        return this.$message.err('查询角色失败')
      }
      //   console.log(roleId)
      console.log(getRes.data)
      this.editForm = getRes.data
      this.editDialogFormVisible = true
    },
    // 添加用户对话框弹出
    showRoleDialog () {
      this.addDialogFormVisible = true
    },
    // 添加用户表单提交
    addRoleInfo () {
      this.$refs.addFormRef.validate(async valid => {
        // console.log(valid)
        if (!valid) return this.$message.error('请输入合法的信息')
        const { data: postRes } = await this.$http.post('roles', { roleName: this.addForm.roleName, roleDesc: this.addForm.roleDesc })
        if (postRes.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.getRoleList()
        this.addDialogFormVisible = false
      })
    },
    // 添加用户对话框关闭
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
    },
    // 编辑角色信息，
    editRoleInfo () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return this.$message.err('请输入合法信息')
        const { data: putRes } = await this.$http.put('roles/' + this.editForm.roleId, { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc })
        console.log(putRes)
        if (putRes.meta.status !== 200) return this.$message.error('更新角色成功')
        this.$message.success('更新角色成功')
        this.getRoleList()
        this.editDialogFormVisible = false
      })
    },
    // 弹出分配权限对话框
    async showRightDailog (role) {
      const { data: getRes } = await this.$http.get('rights/tree')
      if (getRes.meta.status !== 200) return this.$message.error('获取权限信息失败')
      this.rightslist = getRes.data
      console.log(this.rightslist)
      this.getLeafNodes(role, this.defaultkeys)
      this.rightDialogVisible = true
      this.roleId = role.id
    },
    // 将角色的所有三级权限 id值存入 树形默认展开数组
    getLeafNodes (node, arr) {
      if (!node.children) return arr.push(node.id)
      node.children.forEach(element => {
        this.getLeafNodes(element, arr)
      })
    },
    // 点击树形某节点
    handleNodeClick (data) {
      console.log(data)
    },
    // 分配权限对话框
    rightDialogClosed () {
      this.defaultkeys = []
    },
    // 权限确认，提交修改
    async rightInfo () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      const keysStr = keys.join(',')
      const { data: postRes } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: keysStr })
      if (postRes.meta.status !== 200) return this.$message.error('更新权限失败')
      this.$message.success('更新权限成功')
      this.getRoleList()
      this.rightDialogVisible = false
    }
  }
}

</script>

<style lang="less" scoped>
.el-tag {
    margin: 7px;
}

.bdtop {
    border-top: 1px solid #eee;
}

.bdbottom {
    border-bottom: 1px solid #eee;
}
.vertical-center {
    display: flex;
    align-items: center;
}
</style>
